package com.bw.controller.dc;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.dc.PiMaterial;
import com.bw.resp.ResponseResult;
import com.bw.service.dc.IPiMaterialService;
import com.bw.utils.ExportExcel;
import com.bw.utils.ReadExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yzz
 * @since 2020-06-16
 */
@RestController
@RequestMapping("/mater")
public class PiMaterialController {
    @Autowired
    private IPiMaterialService iPiMaterialService;

    //定义日志工具
    private final Logger logger= LoggerFactory.getLogger(PiMaterialController.class);
    /**
     * 查询原材料列表
     */
    @PostMapping("/list/{num}/{size}")
    public ResponseResult list(@PathVariable("num") int num, @PathVariable("size") int size, @RequestBody PiMaterial piMaterial) {
       logger.info("原材料查询开始");
        ResponseResult re = new ResponseResult(false, 400, "查询失败");
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.ne("dstatus",1);//排除已经删除的数据
            if (piMaterial.getName() != null) {//根据名称查询
                qw.like("name", "%" + piMaterial.getName() + "%");
                qw.or();
                qw.like("name", "%" + piMaterial.getChemical() + "%");
            }
            PageHelper.startPage(num, size);//开启分页
            List mlist = iPiMaterialService.list(qw);//查询list
            PageInfo pageInfo = new PageInfo(mlist);//分页后数据
            re.setResult(pageInfo);//存储
            re.setSuccess(true);
            re.setMessage("查询成功");
            logger.info("原材料查询结束");
            return re;
        } catch (Exception e) {
            logger.error("原材料查询失败,{}",e.toString());
            return re;
        }
    }

    /**
     * 查询原材料列表
     */
    @PostMapping("/getMaterial")
    public ResponseResult getMaterial() {
        logger.info("原材料查询2开始");
        ResponseResult re = new ResponseResult(false, 400, "查询失败");
        try {
            List mlist = iPiMaterialService.list();//查询list
            re.setResult(mlist);//存储
            re.setSuccess(true);
            re.setMessage("查询成功");
            logger.info("原材料查询2结束");
            return re;
        } catch (Exception e) {
            logger.error("原材料查询2失败,{}",e.toString());
            return re;
        }
    }
    /**
     * 根据id回显
     *
     * @param id
     * @return
     */
    @PostMapping("/getById/{id}")
    public ResponseResult getById(@PathVariable("id") Long id) {
        logger.info("原材料回显查询开始");
        ResponseResult re = new ResponseResult(false, 400, "查询失败");
        try {
            PiMaterial byId = iPiMaterialService.getById(id);
            re.setSuccess(true);
            re.setMessage("查询成功");
            re.setCode(200);
            re.setResult(byId);//存储
            logger.info("原材料回显查询结束");
            return re;
        } catch (Exception e) {
            logger.error("原材料回显查询失败,{}",e.toString());
            return re;
        }
    }

    /**
     * 添加原材料
     *
     * @param piMaterial
     * @return
     */
    @PostMapping("/save")
    public ResponseResult save(@RequestBody PiMaterial piMaterial) {
        logger.info("原材料添加开始");
        ResponseResult re = new ResponseResult(false, 400, "操作失败");
        try {
            if (piMaterial != null) {//不为空时添加
                piMaterial.setDstatus(0);//默认未删除
                if (piMaterial.getId() != null) {
                    iPiMaterialService.saveOrUpdate(piMaterial);
                    re.setMessage("修改成功");
                } else {
                    iPiMaterialService.save(piMaterial);
                    re.setMessage("添加成功");
                }
            }
            re.setSuccess(true);
            logger.info("原材料添加结束");
            return re;
        } catch (Exception e) {
            logger.error("原材料添加失败,{}",e.toString());
            return re;
        }
    }

    /**
     * 根据id删除材料(需要逻辑删除)
     *
     * @param id
     * @return
     */
    @PostMapping("/del/{id}")
    public ResponseResult delById(@PathVariable("id") Long id) {
        logger.info("原材料逻辑删除开始");
        ResponseResult re = new ResponseResult(false, 400, "删除失败");
        try {
            //查找对应材料
            PiMaterial byId = iPiMaterialService.getById(id);
            byId.setDstatus(1);//修改删除状态为1，已删除
            iPiMaterialService.saveOrUpdate(byId);//保存
            re.setSuccess(true);
            re.setMessage("删除成功");
            logger.info("原材料逻辑删除结束");
            return re;
        } catch (Exception e) {
            logger.error("原材料逻辑删除失败,{}",e.toString());
            return re;
        }
    }

    /**
     * 文件导入
     *
     * @param file
     * @return
     */
    @PostMapping("/imporExcel")
    public ResponseResult imporExcel(MultipartFile file) {
        logger.info("原材料导入开始");
        ResponseResult re = new ResponseResult(false, 400, "上传失败");
        try {
            //获取后缀
            String hou = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'), file.getOriginalFilename().length());
            InputStream in = file.getInputStream();
            //调用封装工具类，处理数据
            List<Map> readExcel = ReadExcel.readExcel(hou, in);
            String jsonString = JSON.toJSONString(readExcel);//转成string
            System.out.println(jsonString);
            List<PiMaterial> plist = JSON.parseArray(jsonString, PiMaterial.class);//转成对象集合
            //保存
            iPiMaterialService.saveBatch(plist);
            re.setSuccess(true);
            re.setMessage("上传成功");
            logger.info("原材料导入结束");
            return re;
        } catch (Exception e) {
            logger.error("原材料导入失败,{}",e.toString());
            return re;
        }
    }

    /**
     * 文件导出
     * @param response
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) {
        logger.info("原材料导出开始");
        QueryWrapper qw = new QueryWrapper();
        qw.ne("dstatus",1);//排除已经删除的数据
        List mlist = iPiMaterialService.list(qw);//查询list
        String path="xls/materil.xls";
        try {
            //ExportExcel.exportExcel(response,mlist,"测试原材料导出","materil.xls");//调用工具类导出数据
            ExportExcel.exportExcel(response,mlist,"测试原材料导出",path);//调用工具类导出数据
            logger.info("原材料导出结束");
        } catch (Exception e) {
            logger.error("原材料导出失败,{}",e.toString());
            e.printStackTrace();
        }
    }
}
